package com.geek.factory.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.dto.ProductInStockDTO;
import com.geek.factory.entity.Product;
import com.geek.factory.result.Result;
import com.geek.factory.service.IProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品管理控制器
 */
@RestController
@RequestMapping("/product")
@Api(tags = "后台系统的 - 产品模块")
@Slf4j
@CrossOrigin
public class ProductController {

    @Autowired
    private IProductService productService;

    /**
     * 生成产品编码
     */
    private String generateProductCodeInternal() {
        String prefix = "P";  // P = Product
        String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String timeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmmss"));
        return prefix + dateStr + timeStr;
    }

    @ApiOperation("生成产品编码")
    @GetMapping("/generate-code")
    public Result generateProductCode() {
        try {
            String productCode = generateProductCodeInternal();
            Map<String, String> result = new HashMap<>();
            result.put("productCode", productCode);
            return new Result(SuccessConstant.SUCCESS, "生成成功", result);
        } catch (Exception e) {
            log.error("生成产品编码失败", e);
            return new Result(SuccessConstant.FAIL, "生成失败");
        }
    }

    @ApiOperation("通过ID查询产品信息")
    @GetMapping("/{productId}")
    public Result findProductById(@ApiParam("产品ID") @PathVariable("productId") Integer productId) {
        Product product = productService.getById(productId);
        log.info("product: {}", product);
        if (product != null) {
            return new Result(SuccessConstant.SUCCESS, "ok", product);
        }
        return new Result(SuccessConstant.FAIL, "产品不存在");
    }

    // 新增产品
    @ApiOperation("新增产品")
    @PostMapping
    public Result addProduct(@RequestBody Product product) {
        // 如果没有设置产品编码，自动生成
        if (product.getCode() == null || product.getCode().trim().isEmpty()) {
            product.setCode(generateProductCodeInternal());
        }

        // 设置默认值
        if (product.getCompleteTime() == null) {
            product.setCompleteTime(LocalDateTime.now());
        }

        boolean isSuccess = productService.save(product);
        log.info("新增产品: {}, 结果: {}", product, isSuccess);
        if (isSuccess) {
            return new Result(SuccessConstant.SUCCESS, "新增成功", product);
        }
        return new Result(SuccessConstant.FAIL, "新增失败");
    }
    @ApiOperation("分页查询产品列表")
    @GetMapping("/page")
    public Result getProductPage(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") Integer pageSize,
            @ApiParam("产品编码") @RequestParam(required = false) String productCode,
            @ApiParam("产品名称") @RequestParam(required = false) String productName,
            @ApiParam("型号") @RequestParam(required = false) String model) {

        try {
            Page<Product> page = new Page<>(pageNum, pageSize);
            QueryWrapper<Product> queryWrapper = new QueryWrapper<>();

            // 添加查询条件
            if (StringUtils.isNotBlank(productCode)) {
                queryWrapper.like("code", productCode);
            }
            if (StringUtils.isNotBlank(productName)) {
                queryWrapper.like("name", productName);
            }
            if (StringUtils.isNotBlank(model)) {
                queryWrapper.like("model", model);
            }

            // 按创建时间倒序排列
            queryWrapper.orderByDesc("complete_time");

            Page<Product> result = productService.page(page, queryWrapper);

            Map<String, Object> data = new HashMap<>();
            data.put("records", result.getRecords());
            data.put("total", result.getTotal());
            data.put("size", result.getSize());
            data.put("current", result.getCurrent());
            data.put("pages", result.getPages());

            return new Result(SuccessConstant.SUCCESS, "查询成功", data);
        } catch (Exception e) {
            log.error("分页查询产品失败", e);
            return new Result(SuccessConstant.FAIL, "查询失败: " + e.getMessage());
        }
    }

    @ApiOperation("更新产品")
    @PutMapping("/{productId}")
    public Result updateProduct(@ApiParam("产品ID") @PathVariable("productId") Integer productId,
                                @RequestBody Product product) {
        try {
            product.setId(productId);
            boolean isSuccess = productService.updateById(product);
            log.info("更新产品: {}, 结果: {}", product, isSuccess);
            if (isSuccess) {
                return new Result(SuccessConstant.SUCCESS, "更新成功", product);
            }
            return new Result(SuccessConstant.FAIL, "更新失败");
        } catch (Exception e) {
            log.error("更新产品失败", e);
            return new Result(SuccessConstant.FAIL, "更新失败: " + e.getMessage());
        }
    }

    @ApiOperation("删除产品")
    @DeleteMapping("/{productId}")
    public Result deleteProduct(@ApiParam("产品ID") @PathVariable("productId") Integer productId) {
        try {
            boolean isSuccess = productService.removeById(productId);
            log.info("删除产品ID: {}, 结果: {}", productId, isSuccess);
            if (isSuccess) {
                return new Result(SuccessConstant.SUCCESS, "删除成功");
            }
            return new Result(SuccessConstant.FAIL, "删除失败");
        } catch (Exception e) {
            log.error("删除产品失败", e);
            return new Result(SuccessConstant.FAIL, "删除失败: " + e.getMessage());
        }
    }
    @ApiOperation("批量删除产品")
    @DeleteMapping("/batch")
    public Result batchDeleteProduct(@RequestBody Map<String, List<Integer>> request) {
        try {
            List<Integer> productIds = request.get("productIds");
            if (productIds == null || productIds.isEmpty()) {
                return new Result(SuccessConstant.FAIL, "请选择要删除的产品");
            }

            boolean isSuccess = productService.removeByIds(productIds);
            log.info("批量删除产品IDs: {}, 结果: {}", productIds, isSuccess);
            if (isSuccess) {
                return new Result(SuccessConstant.SUCCESS, "批量删除成功");
            }
            return new Result(SuccessConstant.FAIL, "批量删除失败");
        } catch (Exception e) {
            log.error("批量删除产品失败", e);
            return new Result(SuccessConstant.FAIL, "批量删除失败: " + e.getMessage());
        }
    }
    @ApiOperation("获取产品统计信息")
    @GetMapping("/stats")
    public Result getProductStats() {
        try {
            long totalCount = productService.count();
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalProducts", totalCount);
            return new Result(SuccessConstant.SUCCESS, "获取统计信息成功", stats);
        } catch (Exception e) {
            log.error("获取产品统计信息失败", e);
            return new Result(SuccessConstant.FAIL, "获取统计信息失败: " + e.getMessage());
        }
    }


    /**
     * 创建产品chan
     */
    @PostMapping("/add")
    public Result create(@RequestBody Product product) {
        boolean saved = productService.save(product);
        return saved
                ? new Result(SuccessConstant.SUCCESS, "新增成功")
                : new Result(SuccessConstant.FAIL, "新增失败");
    }

    /**
     * 更新产品
     */
    @PutMapping("/update")
    public Result update(@RequestBody Product product) {
        boolean updated = productService.updateById(product);
        return updated
                ? new Result(SuccessConstant.SUCCESS, "更新成功")
                : new Result(SuccessConstant.FAIL, "更新失败");
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        boolean removed = productService.removeById(id);
        return removed
                ? new Result(SuccessConstant.SUCCESS, "删除成功")
                : new Result(SuccessConstant.FAIL, "删除失败");
    }

    @GetMapping("/get/{id}")
    public Result get(@PathVariable Long id) {
        Product product = productService.getById(id);
        return product != null
                ? new Result(SuccessConstant.SUCCESS, "查询成功", product)
                : new Result(SuccessConstant.FAIL, "产品不存在");
    }

    /**
     * 查询产品列表
     */
    @GetMapping("/list")
    public Result list() {
        List<Product> list = productService.list();
        return new Result(SuccessConstant.SUCCESS, "查询成功", list);
    }

    /**
     * 产品入库
     */
    @PostMapping("/stock")
    public Result inStock(@RequestBody ProductInStockDTO dto) {
        try {
            productService.inStock(dto);
            return new Result(SuccessConstant.SUCCESS, "入库成功");
        } catch (IllegalArgumentException | IllegalStateException e) {
            return new Result(SuccessConstant.FAIL, e.getMessage());
        } catch (Exception e) {
            return new Result(SuccessConstant.FAIL, "入库失败：" + e.getMessage());
        }
    }

    @GetMapping("/completed")
    @ApiOperation("查询已完成产品")
    public Result getCompletedProducts() {
        List<Product> products = productService.getCompletedProducts();
        return new Result(SuccessConstant.SUCCESS, "查询成功", products);
    }


    @GetMapping("/code/{code}")
    @ApiOperation("根据产品编码查询产品")
    public Result getProductByCode(@PathVariable String code) {
        Product product = productService.getByCode(code);
        return product != null
                ? new Result(SuccessConstant.SUCCESS, "查询成功", product)
                : new Result(SuccessConstant.FAIL, "产品不存在");
    }



}